package com.tgy.JUC.SampeLockDemo;

/***
 * @ClassName: SaleTickets
 * @Description: 基本买票例子
 * 线程就是一个单独的资源类，没有任何附属操作！ 实际开发就用这种方式，
 * @Auther: 送你一块二向箔
 * @Date: 16:51 2022/3/10
 * @version : V1.0
 */
public class SaleTicketsSynchronized {
    public static void main(String[] args) throws InterruptedException {
        //并发：多线程操作同一个资源类，把资源丢入线程
        Tickets tickets = new Tickets();
        new Thread(() -> {
            for (int i = 0; i < 6; i++) {
                tickets.sale();
            }
        }, "A").start();
        new Thread(() -> {
            for (int i = 0; i < 6; i++) {
                tickets.sale();
            }
        }, "B").start();
        new Thread(() -> {
            for (int i = 0; i < 6; i++) {
                tickets.sale();
            }
        }, "C").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 6; i++) {
                    tickets.sale();
                }
            }
        }, "D").start();
    }
}

//资源类 oop 包含属性，方法
class Tickets {
    private int num = 20;

    public synchronized void sale() {
        if(num > 0) {
            System.out.println(Thread.currentThread().getName() + "卖出了第" + num-- + "张票，剩余" + num + "张票！");
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
